package com.atguigu.yygh.order.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.rabbit.constant.MqConst;
import com.atguigu.common.rabbit.service.RabbitService;
import com.atguigu.yygh.hosp.client.HospitalFeignClient;
import com.atguigu.yygh.order.mapper.OrderMapper;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.user.client.PatientFeignClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.haust.su.ghyy.common.exception.YyghException;
import com.haust.su.ghyy.common.helper.HttpRequestHelper;
import com.haust.su.ghyy.common.result.ResultCodeEnum;
import com.haust.su.ghyy.enums.OrderStatusEnum;
import com.haust.su.ghyy.model.order.OrderInfo;
import com.haust.su.ghyy.model.user.Patient;
import com.haust.su.ghyy.vo.hosp.ScheduleOrderVo;
import com.haust.su.ghyy.vo.msm.MsmVo;
import com.haust.su.ghyy.vo.order.OrderMqVo;
import com.haust.su.ghyy.vo.order.OrderQueryVo;
import com.haust.su.ghyy.vo.order.SignInfoVo;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author haustsusu
 * @create 2023-05-08-20:26
 */
@Service
public class OrderServiceImpl extends
        ServiceImpl<OrderMapper, OrderInfo> implements OrderService {


    @Autowired
    private PatientFeignClient patientFeignClient;

    @Autowired
    private HospitalFeignClient hospitalFeignClient;

    @Autowired
    private RabbitService rabbitService;

    //生成挂号的订单,在里面可以进行挂号数减一的操作
    @Override
    public Long saveOrder(String scheduleId, Long patientId) {
        //
        System.out.println("这里报错了吗");


        //获取就诊人信息和排班的信息,通过远程调用来进行操作
        Patient patient = patientFeignClient.getPatientOrder(patientId);//获取就诊人信息
        ScheduleOrderVo scheduleOrderVo = hospitalFeignClient.getScheduleOrderVo(scheduleId);//获取排班信息

        System.out.println("两个方法是否正常");


        //测试部分
        System.out.println(patient.toString());
        System.out.println(scheduleOrderVo.toString());


        //当前时间不可以预约时,抛出异常,前端进行判断的同时,后端也进行改变,两层防护
        if(new DateTime(scheduleOrderVo.getStartTime()).isAfterNow()
                || new DateTime(scheduleOrderVo.getEndTime()).isBeforeNow()) {
            throw new YyghException(ResultCodeEnum.TIME_NO);
        }

        //测试部分
        System.out.println("orderImpl部分到这里");
        System.out.println(scheduleOrderVo.getHoscode());

        //这里scheduleOrderVo.getHoscode()的值为1000_0

        //获取签名信息
        SignInfoVo signInfoVo = hospitalFeignClient.getSignInfoVo(scheduleOrderVo.getHoscode());

        System.out.println("到这里了吗");



        //将上面信息添加到orderInfo表内
        OrderInfo orderInfo = new OrderInfo();

        //将scheduleOrderVo数据复制到orderInfo中
        //方法一,使用getset方法将scheduleOrderVo属性注入到orderInfo中

        //方法二,使用BeanUtils工具类,
        BeanUtils.copyProperties(scheduleOrderVo,orderInfo);//方法表示将scheduleOrderVo中的数据复制到orderInfo中去

        //向orderInfo表中加入其他数据
        String outTradeNo = System.currentTimeMillis() + ""+ new Random().nextInt(100);
        orderInfo.setOutTradeNo(outTradeNo);//随机生成订单号

        //分割线------------
        System.out.println("scheduleid为"+scheduleId);
        System.out.println("scheduleOrderVo.getHosScheduleId()"+scheduleOrderVo.getHosScheduleId());
        //分割线------------
        //orderInfo.setScheduleId(scheduleId);//加入scheduleId
        //上面内容改为了下面,这里做了更改
        orderInfo.setScheduleId(scheduleOrderVo.getHosScheduleId());
        orderInfo.setUserId(patient.getUserId());//用户id
        orderInfo.setPatientId(patientId);//就诊人id
        orderInfo.setPatientName(patient.getName());//患者姓名
        orderInfo.setPatientPhone(patient.getPhone());//患者手机号
        orderInfo.setOrderStatus(OrderStatusEnum.UNPAID.getStatus());
        //this.save(orderInfo);

        //分割线--------------------
        System.out.println("方法到orderid前没?");
        //分割线--------------------

        //分割线--------------------
        System.out.println("这里是orderInfo对象内容"+orderInfo.toString());
        //分割线--------------------

        baseMapper.insert(orderInfo);

        //分割线--------------------
        System.out.println("方法到orderid后没?");
        //分割线--------------------

        //生成订单后可以进行预约数减一的操作


        //调用医院接口


        //将调用医院接口需要的参数放在map集合中
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("hoscode",orderInfo.getHoscode());
        paramMap.put("depcode",orderInfo.getDepcode());
        paramMap.put("hosScheduleId",orderInfo.getScheduleId());
        paramMap.put("reserveDate",new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd"));
        paramMap.put("reserveTime", orderInfo.getReserveTime());
        paramMap.put("amount",orderInfo.getAmount());
        paramMap.put("name", patient.getName());
        paramMap.put("certificatesType",patient.getCertificatesType());
        paramMap.put("certificatesNo", patient.getCertificatesNo());
        paramMap.put("sex",patient.getSex());
        paramMap.put("birthdate", patient.getBirthdate());
        paramMap.put("phone",patient.getPhone());
        paramMap.put("isMarry", patient.getIsMarry());
        paramMap.put("provinceCode",patient.getProvinceCode());
        paramMap.put("cityCode", patient.getCityCode());
        paramMap.put("districtCode",patient.getDistrictCode());
        paramMap.put("address",patient.getAddress());
        //联系人
        paramMap.put("contactsName",patient.getContactsName());
        paramMap.put("contactsCertificatesType", patient.getContactsCertificatesType());
        paramMap.put("contactsCertificatesNo",patient.getContactsCertificatesNo());
        paramMap.put("contactsPhone",patient.getContactsPhone());
        paramMap.put("timestamp", HttpRequestHelper.getTimestamp());
        String sign = HttpRequestHelper.getSign(paramMap, signInfoVo.getSignKey());
        paramMap.put("sign", sign);

        //分割线--------------------
        System.out.println("向map中插入数据成功?");
        //分割线--------------------

        //分割线--------------------
        for (Map.Entry<String,Object> entry:paramMap.entrySet()){
            System.out.println("key是"+entry.getKey()+"value是"+entry.getValue().toString());
        }
        //分割线--------------------

        //分割线--------------------
        System.out.println("上面是parammap的值?");
        //分割线--------------------

        //分割线--------------------
        System.out.println("signinfo的值"+signInfoVo.toString());
        //分割线--------------------

        //调用医院系统的接口
        JSONObject result = HttpRequestHelper.sendRequest(paramMap, signInfoVo.getApiUrl()+"/order/submitOrder");

        //分割线--------------------
        System.out.println("调用医院系统的接口没?");
        //分割线--------------------

        //分割线--------------------
        System.out.println("result"+result.toString());
        //分割线--------------------


        if(result.getInteger("code") == 200) {
            JSONObject jsonObject = result.getJSONObject("data");
            //预约记录唯一标识（医院预约记录主键）
            String hosRecordId = jsonObject.getString("hosRecordId");
            //预约序号
            Integer number = jsonObject.getInteger("number");;
            //取号时间
            String fetchTime = jsonObject.getString("fetchTime");;
            //取号地址
            String fetchAddress = jsonObject.getString("fetchAddress");;
            //更新订单
            orderInfo.setHosRecordId(hosRecordId);
            orderInfo.setNumber(number);
            orderInfo.setFetchTime(fetchTime);
            orderInfo.setFetchAddress(fetchAddress);
            baseMapper.updateById(orderInfo);
            //排班可预约数
            Integer reservedNumber = jsonObject.getInteger("reservedNumber");
            //排班剩余预约数
            Integer availableNumber = jsonObject.getInteger("availableNumber");

            //发送mq信息进行更新号源和短信通知

            //分割线-----------------------------------------------------------------------------------------------------
            //发送mq信息更新号源
            OrderMqVo orderMqVo = new OrderMqVo();
            orderMqVo.setScheduleId(scheduleId);
            orderMqVo.setReservedNumber(reservedNumber);
            orderMqVo.setAvailableNumber(availableNumber);

            //短信提示
            MsmVo msmVo = new MsmVo();
            msmVo.setPhone(orderInfo.getPatientPhone());
            //msmVo.setTemplateCode("SMS_**********");//
            String reserveDate =
                    new DateTime(orderInfo.getReserveDate()).toString("yyyy-MM-dd")
                            + (orderInfo.getReserveTime()==0 ? "上午": "下午");
            Map<String,Object> param = new HashMap<String,Object>(){{
                put("title", orderInfo.getHosname()+"|"+orderInfo.getDepname()+"|"+orderInfo.getTitle());
                put("amount", orderInfo.getAmount());
                put("reserveDate", reserveDate);
                put("name", orderInfo.getPatientName());
                put("quitTime", new DateTime(orderInfo.getQuitTime()).toString("yyyy-MM-dd HH:mm"));
            }};
            msmVo.setParam(param);
            orderMqVo.setMsmVo(msmVo);

            //发送
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_ORDER, MqConst.ROUTING_ORDER, orderMqVo);


        } else {
                 throw new YyghException(result.getString("message"), ResultCodeEnum.FAIL.getCode());
             }
        return orderInfo.getId();
    }



    //根据订单id查询订单的详情信息
    @Override
    public OrderInfo getOrder(String orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        return this.packOrderInfo(orderInfo);
    }



    //订单列表（条件查询带分页）
    @Override
    public IPage<OrderInfo> selectPage(Page<OrderInfo> pageParam, OrderQueryVo orderQueryVo) {
        //orderQueryVo获取条件值
        String name = orderQueryVo.getKeyword(); //医院名称
        Long patientId = orderQueryVo.getPatientId(); //就诊人名称
        String orderStatus = orderQueryVo.getOrderStatus(); //订单状态
        String reserveDate = orderQueryVo.getReserveDate();//安排时间
        String createTimeBegin = orderQueryVo.getCreateTimeBegin();
        String createTimeEnd = orderQueryVo.getCreateTimeEnd();
        //对条件值进行非空判断
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("hosname",name);
        }
        if(!StringUtils.isEmpty(patientId)) {
            wrapper.eq("patient_id",patientId);
        }
        if(!StringUtils.isEmpty(orderStatus)) {
            wrapper.eq("order_status",orderStatus);
        }
        if(!StringUtils.isEmpty(reserveDate)) {
            wrapper.ge("reserve_date",reserveDate);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<OrderInfo> pages = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pages.getRecords().stream().forEach(item -> {
            this.packOrderInfo(item);
        });
        return pages;

    }


    //私有方法,内部处理
    private OrderInfo packOrderInfo(OrderInfo orderInfo) {
        orderInfo.getParam().put("orderStatusString", OrderStatusEnum.getStatusNameByStatus(orderInfo.getOrderStatus()));
        return orderInfo;
    }


}

